<template>
  <div>
    <el-dialog :visible.sync="visible"
               :title="title"
               width="60%"
               :append-to-body="true"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="submitData"
               label-position="right"
               label-width="180px"
               ref="formValidate"
               :rules="ruleValidate">
        <el-form-item label="产品类型：" prop="serviceCode">
          <el-select v-model="submitData.serviceCode"
                     clearable
                     filterable
                     :disabled="!eidtType"
                     @change="handleChangeService"
                     style="width: 260px"
                     placeholder="请选择产品类型">
            <el-option v-for="item in productTypeList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="服务医院：" prop="serviceHospitalDtoList">
          <el-select v-model="submitData.serviceHospitalDtoList"
                     clearable
                     filterable
                     multiple
                     @change="handleChangeHospital"
                     :disabled="!eidtHospital"
                     style="width: 260px"
                     placeholder="请选择服务医院">
            <el-option v-for="item in hospitalList"
                       :key="item.hospitalId"
                       :label="item.name"
                       :value="item.hospitalId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择四高产品：" v-if="submitData.serviceCode=='fourHighService'" prop="businessDtoList">
          <el-select v-model="submitData.businessDtoList"
                     clearable
                     filterable
                     multiple
                     style="width: 360px"
                     placeholder="请选择产品类型">
            <el-option v-for="item in fourHighProductList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.hospitalName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择胎心产品：" v-if="submitData.serviceCode=='fetalHeartRateService'" prop="businessDtoList">
          <el-select v-model="submitData.businessDtoList"
                     clearable
                     filterable
                     multiple
                     style="width: 360px"
                     placeholder="请选择产品类型">
            <el-option v-for="item in fourHighProductList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.hospitalName }}</span>
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="是否包含医联体单位：" class="is-required">
          <el-radio-group v-model="submitData.containsUnion"
                          :disabled="submitData.serviceCode!='personalService'&&submitData.serviceCode!='familyService'">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="推荐内容：" v-if="submitData.serviceCode=='healthCheckService'">
          <el-radio-group v-model="submitData.recommendAll" @change="submitData.healthCheckDtoList=[]">
            <el-radio :label="1">全部健康筛查</el-radio>
            <el-radio :label="0">指定产品</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="submitData.recommendAll==0&&submitData.serviceCode=='healthCheckService'">
          <el-card class="box-card" style="width: 400px">
            <el-tree
              :data="treedata"
              show-checkbox
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              :default-checked-keys="defaultCheckedKeys"
              :props="defaultProps"
              @check="handleCheckChange">
            </el-tree>
          </el-card>

        </el-form-item>

        <el-form-item label="配置位置：" prop="position">
          <el-checkbox-group v-model="submitData.position">
            <el-checkbox label="1">个人类自选自配</el-checkbox>
            <el-checkbox label="2">家庭类自选自配</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <p align="center">
        <el-button @click="modalClose"
                   type="info">取 消
        </el-button>
        <el-button type="primary"
                   v-prevent-re-click
                   @click="handleSubmit()">确 认
        </el-button>
      </p>

    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "optionalConfigUpdateDialog",
  props: {
    optionalConfiglData: {
      type: Object,
      default: {}
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      title: '新 增',
      submitData: {
        companyId: '',
        hospitalId: '',
        serviceCode: '',
        containsUnion: 1,
        position: [],
        recommendAll: 1,
        serviceHospitalDtoList: [],
        healthCheckDtoList: [],
        businessDtoList: [],

      },
      hospitalList: [],
      fourHighServiceList: [],
      fetalHeartRateServiceList: [],
      productTypeList: [
        {
          name: '家庭医生包',
          id: 'familyService'
        }, {
          name: '私人医生包',
          id: 'personalService'
        }, {
          name: '健康风险查',
          id: 'healthCheckService'
        }, {
          name: '远程四高监测',
          id: 'fourHighService'
        }, {
          name: '远程胎心监测',
          id: 'fetalHeartRateService'
        }
      ],//产品类型
      treedata: [],
      defaultProps: {
        label: 'name',
        children: 'packageDtoList'
      },
      defaultExpandedKeys: [],//默认展开节点id
      defaultCheckedKeys: [],//默认勾选节点id
      organization: '',//机构（医院和B端）,
      fourHighProductList: [],
      eidtType: true,
      eidtHospital: true,
      ruleValidate: {
        serviceCode: [{required: true, message: '请选择产品类型', trigger: 'blur'}],
        serviceHospitalDtoList: [{required: true, message: '请选择服务医院', trigger: 'blur'}],
        businessDtoList: [{required: true, message: '请选择产品', trigger: 'blur'}],
        position: [{required: true, message: '请选择配置位置', trigger: 'blur'}],
      },
    }
  },
  created() {
    this.organization = this.optionalConfiglData.organization//获取机构
    if (this.organization === 'bclient') {
      //B端
      this.submitData.companyId = this.optionalConfiglData.companyid
    } else if (this.organization === 'hospital') {
      //医院
      this.submitData.hospitalId = this.optionalConfiglData.hospitalid
    }


    if (this.optionalConfiglData.id) {
      //编辑
      this.title = '编辑'
      this.eidtType = false
      this.submitData = this.optionalConfiglData
      console.log('submitData',this.submitData)
      if (this.submitData.serviceCode === 'fourHighService') {
        //四高查询医院
        this.getRemoteFourHighHospitalList()
        this.submitData.businessDtoList = this.submitData.businessDtoList.map(item => item.productId)
      } else if (this.submitData.serviceCode === 'fetalHeartRateService') {
        //胎心查询医院
        this.getHasHeartRateHospitalList()
        this.submitData.businessDtoList = this.submitData.businessDtoList.map(item => item.productId)
      } else {
        //其他
        this.getAllTypeWithPackages()//查询树
        this.getCompanyList()//查询医院列表
      }
      if (this.submitData.serviceHospitalDtoList && this.submitData.serviceHospitalDtoList.length > 0) {
        this.submitData.serviceHospitalDtoList = this.submitData.serviceHospitalDtoList.map(item => item.hospitalId)
      } else {
        this.$set(this.submitData, 'serviceHospitalDtoList', [])
      }
      let healthCheckDtoList = this.submitData.healthCheckDtoList;
      if (healthCheckDtoList && healthCheckDtoList.length > 0) {
        healthCheckDtoList.forEach(item => {
          if (item.healthRiskTypeId) {
            this.defaultExpandedKeys.push(item.healthRiskTypeId)
          }
        })
        this.defaultCheckedKeys = healthCheckDtoList.map(item => item.healthCheckPackageId)
      }
    } else {
      //新增
      this.title = '新增'
      this.eidtType = true

    }


  },
  methods: {
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    //选择产品类型
    handleChangeService() {
      this.submitData.serviceHospitalDtoList = []
      this.submitData.businessDtoList = []
      if (this.submitData.serviceCode === 'fourHighService') {
        //四高查询医院
        this.getRemoteFourHighHospitalList()
      } else if (this.submitData.serviceCode === 'fetalHeartRateService') {
        //胎心查询医院
        this.getHasHeartRateHospitalList()
      } else {
        //其他
        this.getAllTypeWithPackages()//查询树
        this.getCompanyList()//查询医院列表
      }

    },
    handleSubmit() {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          let mydata = JSON.parse(JSON.stringify(this.submitData));
          if (mydata.serviceHospitalDtoList.length === 0) {
            this.$message.error('请至少选择一个医院')
          } else {
            mydata.serviceHospitalDtoList = mydata.serviceHospitalDtoList.map(item => ({
              hospitalId: item
            }))
            if (this.submitData.serviceCode === 'fourHighService'||this.submitData.serviceCode === 'fetalHeartRateService'){
              mydata.businessDtoList = mydata.businessDtoList.map(item => ({
                productId: item
              }))
            }

            this.post(this.api.company.saveCustom, mydata).then((res) => {
              if (res.data.code === '200') {
                this.$message.success('更新成功')
                this.modalClose()
                this.$parent.getList()
              }
            })
          }
        }
      })


    },
    //查询健康筛查
    getAllTypeWithPackages() {
      this.post(this.api.company.getAllTypeWithPackages).then((res) => {
        if (res.data.code === '200') {
          this.treedata = res.data.object
        }
      })
    },
    //查询医院
    getCompanyList() {
      this.post(this.api.company.getHospitalList, {
        pageSize: 200
      }).then(res => {
        if (res.data.code === '200') {
          this.eidtHospital = true
          this.hospitalList = res.data.object;
          //医院
          if (this.organization === 'hospital' && this.submitData.serviceHospitalDtoList.indexOf(this.optionalConfiglData.hospitalid) === -1) {
            if (this.hospitalList.map(item => item.hospitalId).indexOf(this.optionalConfiglData.hospitalid) !== -1) {
              this.submitData.serviceHospitalDtoList.unshift(this.optionalConfiglData.hospitalid)
            }
          }

        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    //查询四高医院
    getRemoteFourHighHospitalList() {
      let terminalId = ''
      let id=null
      if (this.organization === 'hospital') {
        //医院
        terminalId = this.optionalConfiglData.hospitalid
        id = this.optionalConfiglData.hospitalid
      } else {
        //B端
        terminalId = this.optionalConfiglData.companyid
      }
      this.post(this.api.company.getRemoteFourHighHospitalList, {
        pageSize: 200,
        id:id
      }).then(res => {
        if (res.data.code === '200') {
          this.hospitalList = res.data.object;
          this.hospitalList.forEach(item => {
            this.$set(item, 'hospitalId', item.id)
          })

          if (this.hospitalList.map(item => item.hospitalId).indexOf(terminalId) === -1 && this.organization === 'hospital') {
            //没有配置四高医院，不能继续编辑
            this.$message.warning('该医院没有开通该项目，请先开通')
            this.eidtHospital = false
          } else {
            if (this.organization === 'hospital' && this.submitData.serviceHospitalDtoList.indexOf(this.optionalConfiglData.hospitalid) === -1) {
              //医院
              if (this.hospitalList.map(item => item.hospitalId).indexOf(this.optionalConfiglData.hospitalid) !== -1) {
                this.submitData.serviceHospitalDtoList.unshift(this.optionalConfiglData.hospitalid)
              }
            }
            this.getRemoteFourHighProductList()
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    //查询胎心医院
    getHasHeartRateHospitalList() {
      let terminalId = ''
      let id=null
      if (this.organization === 'hospital') {
        //医院
        terminalId = this.optionalConfiglData.hospitalid
        id = this.optionalConfiglData.hospitalid
      } else {
        //B端
        terminalId = this.optionalConfiglData.companyid
      }
      this.post(this.api.company.getHasHeartRateHospitalList, {
        pageSize: 200,
        id:id
      }).then(res => {
        if (res.data.code === '200') {
          this.hospitalList = res.data.object;
          this.hospitalList.forEach(item => {
            this.$set(item, 'hospitalId', item.id)
          })
          if (this.hospitalList.map(item => item.hospitalId).indexOf(terminalId) === -1 && this.organization === 'hospital') {
            //没有配置四高医院，不能继续编辑
            this.$message.warning('该医院没有开通该项目，请先开通')
            this.eidtHospital = false
          } else {
            if (this.organization === 'hospital' && this.submitData.serviceHospitalDtoList.indexOf(this.optionalConfiglData.hospitalid) === -1) {
              //医院
              if (this.hospitalList.map(item => item.hospitalId).indexOf(this.optionalConfiglData.hospitalid) !== -1) {
                this.submitData.serviceHospitalDtoList.unshift(this.optionalConfiglData.hospitalid)
              }
            }
            this.getFetalHeartRateServiceList()
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    //查询四高产品
    getRemoteFourHighProductList() {
      this.post(this.api.company.getRemoteFourHighProductList, {
        hospitalIds: this.submitData.serviceHospitalDtoList
      }).then(res => {
        if (res.data.code === '200') {
          this.fourHighProductList = res.data.object;
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    //查询胎心产品
    getFetalHeartRateServiceList() {
      this.post(this.api.company.getFetalHeartRateServiceList, {
        pageSize: 200
      }).then(res => {
        if (res.data.code === '200') {
          this.fourHighProductList = res.data.object;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    //选择医院
    handleChangeHospital(val) {
      if (this.organization === 'hospital') {
        //医院
        if (val.indexOf(this.optionalConfiglData.hospitalid) === -1) {
          this.$message.warning('不能删除自身医院')
          this.submitData.serviceHospitalDtoList.unshift(this.optionalConfiglData.hospitalid)
        }
        if (this.submitData.serviceCode === 'fourHighService') {
          //四高
          this.getRemoteFourHighProductList()
        }
        if (this.submitData.serviceCode === 'fetalHeartRateService') {
          //胎心
          this.getFetalHeartRateServiceList()
        }

      }

    },

    handleCheckChange(obj, selectObj) {
      let checkedNodes = selectObj.checkedNodes;
      this.submitData.healthCheckDtoList = checkedNodes.map(item => ({
        healthRiskTypeId: item.healthRiskTypeId ? item.healthRiskTypeId : '',
        healthCheckPackageId: item.id ? item.id : ''
      }))
    },
  }
}
</script>

<style scoped>

</style>
